package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult;
import com.foxinmy.weixin4j.mp.api.NotifyApi;
import com.foxinmy.weixin4j.mp.message.NotifyMessage;
import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.mp.model.TemplateMessageInfo;
import com.foxinmy.weixin4j.token.TokenHolder;
import com.foxinmy.weixin4j.tuple.NotifyTuple;
import com.foxinmy.weixin4j.util.NameValue;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.wechat.api.YgTmplApi;
import com.ygqh.baby.service.wechat.message.YgSubscribeTempMsg;
import com.ygqh.baby.service.wechat.message.YgTemplateMessage;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.YgStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxMpMessageServiceImpl extends BaseWxMpMessageService implements WxMpMessageService {
    protected final Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;
    @Autowired
    private WxSmallAuthorityService wxSmallAuthorityService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgOrderService ygOrderService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisDao redisDao;
    @Value("${promotion.link}")
    protected String promotionLink;
    @Value("${micro.msg.appId}")
    protected String appId;

    @Override
    public TemplateMessage getTemplateMessageInfo(YgOrder order, YgUser user, WxMessageType mType) {

        String openId = user.getOpenId();
        if (openId == null) {
            return null;
        }

        TemplateMessage tplMessage = null;
        List<TemplateMessageInfo> list = this.getTemplateMessageList();
        String dzfTemplateId = "";
        String zfcgTemplateId = "";
        String spfhTemplateId = "";
        String ddwcTemplateId = "";
        for (TemplateMessageInfo temp : list) {
            if ("订单支付成功".equals(temp.getTitle())) {
                zfcgTemplateId = temp.getTemplateId();
            }
            if ("订单待支付通知".equals(temp.getTitle())) {
                dzfTemplateId = temp.getTemplateId();
            }
            if ("商品已发出通知".equals(temp.getTitle())) {
                spfhTemplateId = temp.getTemplateId();
            }
            if ("订单完成通知".equals(temp.getTitle())) {
                ddwcTemplateId = temp.getTemplateId();
            }
        }
        String url = promotionLink + "/user/orderdetail.html?orderId=" + order.getOrderId();
        if (WxMessageType.PayInvitation.equals(mType)) {
            // String templateId =
            // "SzmFwomdJ86xNG8-voHIuYE_ydLITPAHzyMaLbVC-G0";
            String title = "亲，您还有需要付款的订单。订单提交后24小时内有效。";
            String tail = "我要付款";
            tplMessage = new TemplateMessage(openId, dzfTemplateId, title, url);

            tplMessage.pushHead("#323232", title);
            tplMessage.pushTail(tail);
            tplMessage.pushItem("keyword1", "#323232", order.getOrderId().toString());
            tplMessage.pushItem("keyword2", "#323232", order.getProductNames() + " 等" + order.getItemCount() + "件");
            tplMessage.pushItem("remark", "#323232", "订单金额：¥" + order.getTotalPrice().toString());

        }
        if (WxMessageType.PaySuccess.equals(mType)) {
            // 推送微信消息
            // String templateId =
            // "fuA08q6RLkthsF-BDEzC-XIZvoISWnCWuwEnRIxHZMQ";
            String title = "亲，您的订单已支付成功。";
            tplMessage = new TemplateMessage(openId, zfcgTemplateId, title, url);

            tplMessage.pushHead("#323232", title);
            tplMessage.pushItem("orderMoneySum", "#323232", "¥" + order.getTotalPrice().toString());
            tplMessage.pushItem("orderProductName", "#323232", order.getOrderDetail().get(0).getProductName() + " 等" + order.getOrderDetail().size() + "件");
            tplMessage.pushItem("Remark", "#323232", "订单编号：" + order.getOrderId().toString());
        }
        if (WxMessageType.WaitingSign.equals(mType)) {
            String title = "亲，您的订单已经发货，请注意查收。";
            tplMessage = new TemplateMessage(openId, spfhTemplateId, title, url);

            tplMessage.pushHead("#323232", title);
            tplMessage.pushItem("delivername", "#323232", order.getExpressCompany());
            tplMessage.pushItem("ordername", "#323232", order.getExpressCode());
            tplMessage.pushItem("remark", "#323232", "订单编号：" + order.getOrderId().toString() + "\n" + "商品名称：" + order.getOrderDetail().get(0).getProductName()
                    + " 等" + order.getOrderDetail().size() + "件");
        }
        if (WxMessageType.TradeSuccess.equals(mType)) {
            String title = "亲，快去壹果评价吧，评价完成后您将收到1张30元代金券！";
            tplMessage = new TemplateMessage(openId, ddwcTemplateId, title, url);

            tplMessage.pushHead("#323232", title);
            tplMessage.pushItem("keyword1", "#323232", order.getOrderId().toString());
            tplMessage.pushItem("keyword2", "#323232", DateConvertUtils.format(order.getConfirmReceiveTime()));
            tplMessage.pushItem("remark", "#323232", "商品详情：" + order.getOrderDetail().get(0).getProductName() + " 等" + order.getOrderDetail().size() + "件");
        }
        return tplMessage;
    }

    @Override
    public Message sendRebateMessage(YgOrder order, YgUser user, BigDecimal rebatePrice, String title, String remark, OperationType operationType) {
        // List<TemplateMessageInfo> list = this.getTemplateMessageList();
        String wxMsgTempId = this.getWxMsgTempId(WxMessageType.Rebate);
        String url = promotionLink + "/discount/index.html?sCode=" + user.getUserName();
        if (user.getUserType().equals(UserType.UserAgent)) {
            url = promotionLink + "/channel/index.html?usertype=useragent";
        }
        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), wxMsgTempId, title, url);
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", order.getOrderId().toString());
        tplMessage.pushItem("keyword2", "#323232", "【壹果】" + promotionLink.substring(7));
        tplMessage.pushItem("keyword3", "#323232", DateConvertUtils.format(order.getCreateTime()));
        tplMessage.pushItem("keyword4", "#323232", "¥" + rebatePrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        tplMessage.pushItem("keyword5", "#323232", operationType.getTitle() + "已入荷");
        tplMessage.pushItem("remark", "#323232", remark);
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendBalanceMessage(Date time, String orderId, YgUser user, BigDecimal rebatePrice, String title, String remark, BalanceType balanceType) {
        String wxMsgTempId = this.getWxMsgTempId(WxMessageType.Rebate);
		/*String url = promotionLink + "/discount/index.html?sCode=" + user.getUserName();
		if (user.getUserType().equals(UserType.UserAgent)) {
			url = promotionLink + "/channel/index.html?usertype=useragent";
		}*/
        String url = promotionLink + "/user/index.html";
        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), wxMsgTempId, title, url);
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", orderId);
        tplMessage.pushItem("keyword2", "#323232", "【壹果】" + promotionLink.substring(7));
        tplMessage.pushItem("keyword3", "#323232", DateConvertUtils.format(time));
        tplMessage.pushItem("keyword4", "#323232", "¥" + rebatePrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        tplMessage.pushItem("keyword5", "#323232", balanceType.getTitle() + "已入荷");
        tplMessage.pushItem("remark", "#323232", remark);
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendOrderSuccessMsg(YgUser user, List<YgOrder> orderList) {
        if (user.getOpenId() == null) {
            return Message.error("该用户openid不存在", user.getUserName());
        }

        String url = promotionLink + "/user/orderlist.html?orderStatus=TradeSuccess";
        String title = "亲，快去壹果评价吧，评价完成后您将收到1张100-20元优惠券！";
        if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
            smsService.sendSms(user.getUserName(), title);
        }
        String msgId = this.getWxMsgTempId(WxMessageType.TradeSuccess);
        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), msgId, title, url);
        YgOrder ygOrder = ygOrderService.findOrderDetailByOrderId(orderList.get(0).getOrderId());
        tplMessage.pushHead("#323232", title);
        if (orderList.size() > 1) {

            tplMessage.pushItem("keyword1", "#323232", ygOrder.getOrderId().toString() + " 等");
        } else {
            tplMessage.pushItem("keyword1", "#323232", ygOrder.getOrderId().toString());

        }
        tplMessage.pushItem("keyword2", "#323232", DateConvertUtils.format(DateConvertUtils.addDay(ygOrder.getConfirmReceiveTime(), -1)));
        tplMessage.pushItem("remark", "#323232", "商品详情：" + ygOrder.getOrderDetail().get(0).getProductName() + " 等商品。");
        Message message = this.sendTemplateMessage(tplMessage);

        return message;
    }

    @Override
    public Message sendOrderSuccessMsg(YgUser user, String url, String title, String remark, String[] keyword) {
        if (!canSend(user)) {
            return Message.error("该用户未绑定微信，或已取关", user.getId());
        }
        Message message = this.sendTemplateMessage(WxMessageType.TradeSuccess, title, remark, user.getOpenId(), url, keyword);

        return message;
    }

    @Override
    public Message sendAudit4Return(String returnCode, ReturnStatus returnStatus, ReturnType returnType, Long userId,
                                    String remark, Long orderId) {
        YgUser user = ygUserService.findById(userId);
        if (user.getOpenId() == null && !YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
            return Message.error("该用户openid和手机号不存在", user.getUserName());
        }
        String auditResult = "已通过";
        // 短信
        String smsContent;

        if (returnStatus.equals(ReturnStatus.Reject)) {
            auditResult = "未通过";
            remark = "未通过原因：" + remark;
            smsContent = "亲，您的" + returnType.getTitle() + "申请" + returnCode + "审核未通过，原因:" + remark;
        } else {
            if (returnStatus.equals(ReturnStatus.WaitingReturnGoods)) {
                // 已发货退货
                smsContent = "亲，您的" + returnType.getTitle() + "申请" + returnCode + "已审核通过。\n" + remark;
            } else {
                // 未发货退货
                smsContent = "亲，您的" + returnType.getTitle() + "申请" + returnCode + ",已于" + DateConvertUtils.format(new Date(), DateConvertUtils.DATE_FORMAT)
                        + "审核通过。";
            }
        }
        YgOrder order = ygOrderService.findByOrderId(orderId);
        if (Constant.YIJIADIAN_PLATFORM_NO.equals(order.getPlatformNo())) {
            if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
                smsService.sendSms(user.getUserName(), smsContent + "可以到\"壹家店 -> 退换货\"查看哦");
            }
            return Message.success(null);
        }
//        String url = promotionLink + "/return/viewProgress.html";
        if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
            smsService.sendSms(user.getUserName(), smsContent);
        }
        return Message.success(null);
    }

    @Override
    public Message sendRedPacketMessage(Long userId, String friendNickName) {
        YgUser user = ygUserService.findById(userId);
        String title = "亲，您邀请的好友在壹果商城买了新商品，送您20元红包，请查收。";
        String url = promotionLink + "/user/account.html";

        if (YgStringUtils.isChinaPhoneLegal(user.getUserName())) {
            // 短信
            smsService.sendSms(user.getUserName(), "亲，您邀请的好友在壹果商城买了新商品，送您20元红包，到壹果商城看看吧");
        }

        String tempId = this.getWxMsgTempId(WxMessageType.BindIngMsg);
        if (user.getOpenId() == null) {
            return Message.error("该用户openid不存在", user.getUserName());
        }

        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, url);
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", user.getUserName());
        tplMessage.pushItem("keyword2", "#323232", "好友【" + friendNickName + "】");
        tplMessage.pushItem("remark", "#323232", "到壹果账户去看看吧。");
        Message message = this.sendTemplateMessage(tplMessage);
        return message;
    }

    @Override
    public Message sendGoods4Change(String expressCompany, String expressCode, String productNames, Long orderId, Long userId) {
        YgUser user = ygUserService.findById(userId);
        if (user.getOpenId() == null) {
            return Message.error("该用户openid不存在", user.getUserName());
        }
        String tempId = this.getWxMsgTempId(WxMessageType.WaitingSign);
        String url = promotionLink + "/return/viewProgress.html";
        String title = "亲，您的换货商品已经发出啦，感谢您对壹果的支持。";
        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("delivername", "#323232", expressCompany);
        tplMessage.pushItem("ordername", "#323232", expressCode);
        tplMessage.pushItem("remark", "#323232", "商品详细：" + productNames + "\n" + "订单编号：" + orderId);

        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendWaitingPay$Samll(YgOrder order, String samllOpenId) {
        String title = "亲，您还有需要付款的订单。订单提交后24小时内有效。";
        String templateId = "Z2NNoBwjLpWjU0DAeTaePsmJt3kCiNgsrZCmbihlKDI";
        String url = "pages/user/orderdetail/orderdetail?orderId=" + order.getOrderId();

        YgTemplateMessage tplMessage = new YgTemplateMessage(samllOpenId, templateId, title, url, order.getFormId());
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", order.getOrderId().toString());
        tplMessage.pushItem("keyword2", "#323232", order.getProductNames() + " 等" + order.getItemCount() + "件");
        tplMessage.pushItem("keyword3", "#323232", "¥" + order.getTotalPrice().toString());
        Message message = this.sendTmplMsg$Small(tplMessage);
        return message;
    }

    @Override
    public Message sendTmplMsg$Small(YgTemplateMessage tplMessage) {
        TokenHolder tokenHolder = wxSmallAuthorityService.findTokenHolder();
        YgTmplApi tmplApi = new YgTmplApi(tokenHolder);
        try {
            JsonResult sendResult = tmplApi.sendTmplMessage(tplMessage);
            if (sendResult.getCode() == 0) {
                return Message.success(sendResult.getText(), null);
            }

            return Message.error(sendResult.toString(), null);
        } catch (WeixinException e) {
            ERROR_MESSAGE.setCode(e.getErrorCode());
            ERROR_MESSAGE.setContent(e.getErrorMsg());
            logger.error("发送小程序模板消息失败；openId=【" + tplMessage.getToUser() + "】【" + tplMessage.getHead() + "】" + e.getMessage());
            e.printStackTrace();
        }
        return ERROR_MESSAGE;
    }

    @Override
    public Message sendAgentAuditMsg(String userName, String openId, CheckStatus checkStatus, String reason) {
        if (StringUtil.isEmpty(openId)) {
            return Message.error("该用户openid不存在", userName);
        }
        String tempId = this.getWxMsgTempId(WxMessageType.AuditResultMsg);
        String title = "亲，您在壹果提交的商品代理申请已审核，请查看。";
        String url = promotionLink + "/channel/index.html?usertype=useragent";
        String auditResult = "已通过";

        if (checkStatus.equals(CheckStatus.Reject)) {
            auditResult = "未通过";
            url = promotionLink + "/discount/index.html?sCode=" + userName;
        }

        TemplateMessage tplMessage = new TemplateMessage(openId, tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", userName);
        tplMessage.pushItem("keyword2", "#323232", auditResult);
        tplMessage.pushItem("keyword3", "#323232", DateConvertUtils.format(new Date(), DateConvertUtils.DATE_FORMAT));
        if (checkStatus.equals(CheckStatus.Reject)) {
            tplMessage.pushItem("remark", "#323232", "未通过原因：" + reason);
        } else {
            tplMessage.pushItem("remark", "#323232", "为获得更多信息，请申请加入代理微信群。请添加 果果微信 :yiigoogg，并回复\"代理入群 + 您的手机号\"");

        }
        Message message = this.sendTemplateMessage(tplMessage);
        return message;
    }

    @Override
    public Message cancelAgentAuditMsg(String userName, String openId, String reason, String url) {
        if (StringUtil.isEmpty(openId)) {
            return Message.error("提示信息未发送，该用户openid不存在！");
        }
        Message message = this.sendTemplateMessage(WxMessageType.CancelAgent, reason, "", openId, promotionLink + url, "壹果代理", "近3个月订单总金额不达标。");
        return message;
    }

    @Override
    public Message sendInviteRegisterSuccessMsg(String openId, String inviterSourceCode, String registerUserName, String registerNickName) {
        if (StringUtil.isBlank(inviterSourceCode)) {
            return Message.error(inviterSourceCode + "为空");
        }

        if (StringUtil.isEmpty(openId)) {
            logger.warn("发送邀请注册成功消息失败，该用户没有openId");
            return Message.error("该用户openid不存在", inviterSourceCode);
        }
        String tempId = this.getWxMsgTempId(WxMessageType.InviteRegisterSuccess);
        String title = "亲，有朋友通过您的邀请注册壹果了。";
        String url = promotionLink + "/user/index.html";

        TemplateMessage tplMessage = new TemplateMessage(openId, tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", registerNickName);
        tplMessage.pushItem("keyword2", "#323232", registerUserName.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        tplMessage.pushItem("keyword3", "#323232", DateConvertUtils.format(new Date(), DateConvertUtils.DATE_FORMAT));
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendNewReviewMsg(String title, String nickName, Long userId, Long publishId) {
        YgUser user = ygUserService.findById(userId);
        if (StringUtil.isEmpty(user.getOpenId())) {
            logger.warn("发送新赞/评论消息失败，该用户没有openId");
            return Message.error("该用户openid不存在", userId);
        }
        String tempId = this.getWxMsgTempId(WxMessageType.NewReview);
        String url = promotionLink + "/share/comment.html?publishId=" + publishId;

        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", nickName);
        tplMessage.pushItem("keyword2", "#323232", DateConvertUtils.format(new Date(), DateConvertUtils.DATE_FORMAT));
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendGrowthFundMsg(String title, BigDecimal price, Date time, String content, Long userId) {
        YgUser user = ygUserService.findById(userId);
        if (StringUtil.isEmpty(user.getOpenId())) {
            logger.warn("成长基金到账消息失败，该用户没有openId");
            return Message.error("该用户openid不存在", userId);
        }

        String remark = "请到 \"成长角落/成长基金 \"中查看";
        String url = promotionLink + "/discount/index.html?sCode=" + user.getUserName();

        if (user.getUserType().equals(UserType.UserAgent)) {
            remark = "请到 \"代理中心/可提现金额\"中查看";
            title = "亲，您有一笔新的收入到账哦。";
            url = promotionLink + "/channel/index.html?usertype=useragent";
        }
        String tempId = this.getWxMsgTempId(WxMessageType.GrowthFundMsg);

        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", "¥" + price.toString());
        tplMessage.pushItem("keyword2", "#323232", DateConvertUtils.format(new Date(), DateConvertUtils.DATE_FORMAT));
        tplMessage.pushItem("keyword3", "#323232", content + "\n" + remark);
        // tplMessage.pushItem("remark", "#323232", "请到 \"成长角落/成长基金 \"中查看");
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendGroupOrderRemindMsg(String title, String remainingTime, Long lastAmount, String url, Long userId) {
        YgUser user = ygUserService.findById(userId);
        if (StringUtil.isEmpty(user.getOpenId())) {
            logger.warn("拼团未成功提醒消息失败，该用户没有openId");
            return Message.error("该用户openid不存在", userId);
        }
        String tempId = this.getWxMsgTempId(WxMessageType.GroupOrderRemind);

        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", remainingTime);
        tplMessage.pushItem("keyword2", "#323232", lastAmount + "人");
        tplMessage.pushItem("remark", "#323232", "快去分享给您的好友一起拼团吧. ");
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendActionMsg(String first, String link, String keyword1, String openId, String keyword2, String keyword3, String keyword4, String remark) {

        String tempId = this.getWxMsgTempId(WxMessageType.NewAction);
        TemplateMessage tplMessage = new TemplateMessage(openId, tempId, first, link);
        tplMessage.pushHead("#2e82ff", first);

        tplMessage.pushItem("keyword1", "#323232", keyword1);
        tplMessage.pushItem("keyword2", "#323232", keyword2);
        tplMessage.pushItem("keyword3", "#323232", keyword3);
        tplMessage.pushItem("keyword4", "#323232", keyword4);
        tplMessage.pushItem("remark", "#999", remark);
        Message message = this.sendTemplateMessage(tplMessage);
        return message;
    }

    @Override
    public Message sendBindMsg(String first, String link, String keyword1, String openId, String keyword2, String remark) {

        String tempId = this.getWxMsgTempId(WxMessageType.BindIngMsg);
        TemplateMessage tplMessage = new TemplateMessage(openId, tempId, first, link);
        tplMessage.pushHead("#2e82ff", first);
        tplMessage.pushItem("keyword1", "#323232", keyword1);
        tplMessage.pushItem("keyword2", "#323232", keyword2);

        tplMessage.pushItem("remark", "#999", remark);
        Message message = this.sendTemplateMessage(tplMessage);
        return message;
    }

    @Override
    public Message sendBindMsg(String first, String link, String remark, YgUser user, String... keyword) {

        Boolean canSend = this.canSend(user);
        if (!canSend) {
            return Message.error("该用户未绑定微信，或已取关", user.getId());
        }

        link = promotionLink + link;
        Message message = this.sendTemplateMessage(WxMessageType.BindIngMsg, first, remark, user.getOpenId(), link, keyword);

        return message;
    }

    @Override
    public Message sendServiceExpressMsg(String first, String link, String keyword1, String keyword2, String openId, String keyword3, String remark) {

        String tempId = this.getWxMsgTempId(WxMessageType.ProductService);

        TemplateMessage tplMessage = new TemplateMessage(openId, tempId, first, link);
        tplMessage.pushHead("#2e82ff", first);
        tplMessage.pushItem("keyword1", "#323232", keyword1);
        tplMessage.pushItem("keyword2", "#323232", keyword2);
        tplMessage.pushItem("keyword3", "#323232", keyword3);

        tplMessage.pushItem("remark", "#999", remark);
        Message message = this.sendTemplateMessage(tplMessage);
        return message;
    }

    @Override
    public Message sendOrderPaySuccessMsg(String title, Long orderId, String openId, BigDecimal totalPrice, String productName, int goodsType, String url) {

        // 推送微信消息
        if (StringUtil.isBlank(title)) {
            title = "亲，您的订单已支付成功。";
        }

        String wxMsgTempId = this.getWxMsgTempId(WxMessageType.PaySuccess);
        TemplateMessage tplMessage = new TemplateMessage(openId, wxMsgTempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("orderMoneySum", "#323232", "¥" + totalPrice);
        tplMessage.pushItem("orderProductName", "#323232", productName + " 等" + goodsType + "件");
        tplMessage.pushItem("Remark", "#323232", "订单编号：" + orderId);

        Message message = this.sendTemplateMessage(tplMessage);
        if (message.getType().equals(Message.Type.error)) {
            logger.error("发送支付微信消息失败....订单编号:" + orderId);
        }
        return message;
    }

    @Override
    public Message sendSubscribeMsg(String openId, String title, String templateId, String url, String scene, String content) {
        YgSubscribeTempMsg tmpMsg = new YgSubscribeTempMsg(openId, templateId, title, url, scene);

        tmpMsg.pushItem("content", "#323232", content);
        System.out.println(tmpMsg.toString());
        return this.sendSubscribeMsg(tmpMsg);
    }

    @Override
    public Message sendSubscribeMsg(YgSubscribeTempMsg subscribeTempMsg) {
        TokenHolder tokenHolder = wxMpAuthorityService.findTokenHolder();
        YgTmplApi tmplApi = new YgTmplApi(tokenHolder);
        try {
            JsonResult result = tmplApi.sendTmplMessage(subscribeTempMsg);
            return Message.success(result.getDesc(), null);
        } catch (WeixinException e) {
            e.printStackTrace();
            return Message.error(e.getMessage(), null);
        }
    }

    @Override
    public Message sendCustomMsg(NotifyTuple notifyTuple, String to) {
        return sendCustomMsg(notifyTuple, to, Constant.YIIGOO_PLATFORM_NO);
    }

    @Override
    public Message sendCustomMsg(NotifyTuple notifyTuple, String to, String platformNo) {
        NotifyMessage notifyMessage = new NotifyMessage(to, notifyTuple);
        NotifyApi notifyAPI = new NotifyApi(wxMpAuthorityService.findTokenHolder(platformNo));
        try {
            notifyAPI.sendNotify(notifyMessage);
            return Message.success(null);
        } catch (WeixinException e) {
            e.printStackTrace();
            return Message.error(e.getMessage(), null);
        }
    }

    @Override
    public Message sendOrderPaySuccessMsg(Long userId, Long orderId, BigDecimal orderPrice, String productName, int size) {
        YgUser user = ygUserService.findById(userId);
        if (!this.canSend(user)) {
            return Message.error("该用户不满足发送条件", null);
        }
        String tempId = this.getWxMsgTempId(WxMessageType.PaySuccess);
        // 推送微信消息
        String title = "亲，您的订单已支付成功。";
        String url = promotionLink + "/user/orderdetail.html?orderId=" + orderId;
        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("orderMoneySum", "#323232", "¥" + orderPrice.toString());
        tplMessage.pushItem("orderProductName", "#323232", productName + " 等" + size + "件");
        tplMessage.pushItem("Remark", "#323232", "订单编号：" + orderId.toString());

        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendOrderSendMsg(String title, String orderId, String expressCompany, String expressCode, String productName, String openId) {

        Map<String, NameValue> nameValue = new HashMap<String, NameValue>();

        NameValue n = new NameValue(null, title);
        nameValue.put("first", n);
        n = new NameValue(null, expressCompany);
        nameValue.put("delivername", n);
        n = new NameValue(null, expressCode);
        nameValue.put("ordername", n);
        String remark = "订单编号：" + orderId + "\n" + "商品名称：" + productName;
        n = new NameValue(null, remark);
        nameValue.put("remark", n);
        String url = promotionLink + "/user/orderdetail.html?orderId=" + orderId;
        Boolean canSend = this.canSend(openId);

        if (!canSend) {
            return Message.error("该用户未绑定微信，或已取关", orderId);
        }

        return this.sendTemplateMessage(WxMessageType.WaitingSign, openId, url, nameValue);
    }

    @Override
    public Message sendCouponMsg(String title, String link, YgUser user, String... keywords) {
        Boolean canSend = this.canSend(user);
        if (!canSend) {
            return Message.error("该用户未绑定微信，或已取关", user.getId());
        }
        link = promotionLink + link;
        // 发送微信模板消息
        String tempId = this.getWxMsgTempId(WxMessageType.GrowthFundMsg);
        TemplateMessage tplMessage = new TemplateMessage(user.getOpenId(), tempId, title, link);
        tplMessage.pushHead("#323232", title);
        for (int i = 0; i < keywords.length; i++) {
            tplMessage.pushItem("keyword" + (i + 1), "#323232", keywords[i]);
        }
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendOverdueReminder(YgUser ygUser, String title, String link, String remark, String... keywords) {
        if (ygUser == null || StringUtils.isBlank(ygUser.getOpenId())) {
            return Message.error("该用户未绑定微信，或已取关", ygUser.getId());
        }
        link = promotionLink + link;
        // 发送微信模板消息
        String tempId = this.getWxMsgTempId(WxMessageType.OverdueReminder);
        TemplateMessage tplMessage = new TemplateMessage(ygUser.getOpenId(), tempId, title, link);
        tplMessage.pushHead("#323232", title);
        for (int i = 0; i < keywords.length; i++) {
            tplMessage.pushItem("keyword" + (i + 1), "#323232", keywords[i]);
        }
        tplMessage.pushItem("remark", "#323232", remark);
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendOrderDispatchNotice(YgUser ygUser, String title, String logisticName, String expressCode, String link, String remark) {

        if (ygUser == null || StringUtils.isBlank(ygUser.getOpenId())) {
            return Message.error("该用户未绑定微信，或已取关", ygUser.getId());
        }
        link = promotionLink + link;
        // 发送微信模板消息
        String tempId = this.getWxMsgTempId(WxMessageType.OrderDispatchNotice);
        TemplateMessage tplMessage = new TemplateMessage(ygUser.getOpenId(), tempId, title, link);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", logisticName);
        tplMessage.pushItem("keyword2", "#323232", expressCode);
        tplMessage.pushItem("remark", "#323232", remark == null ? "" : remark);
        return this.sendTemplateMessage(tplMessage);

    }

    @Override
    public Message sendOrderReceiptNotice(YgUser ygUser, String title, String orderCode, String recipienter, Date recipientTime, String link, String remark) {

        if (ygUser == null || StringUtils.isBlank(ygUser.getOpenId())) {
            return Message.error("该用户未绑定微信，或已取关", ygUser.getId());
        }
        // 发送微信模板消息
        String tempId = this.getWxMsgTempId(WxMessageType.OrderReceiptNotice);
        String url = promotionLink + link;
        TemplateMessage tplMessage = new TemplateMessage(ygUser.getOpenId(), tempId, title, url);

        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", orderCode);
        tplMessage.pushItem("keyword2", "#323232", recipienter);
        tplMessage.pushItem("keyword3", "#323232", DateConvertUtils.formatDateTime(recipientTime));
        tplMessage.pushItem("remark", "#323232", remark == null ? "" : remark);
        return this.sendTemplateMessage(tplMessage);

    }

    @Override
    public Message sendMemberUpgrade(YgUser ygUser, String title, String memberLevel, String checkStatus, String remark, String link) {
        if (ygUser == null || StringUtils.isBlank(ygUser.getOpenId())) {
            return Message.error("该用户未绑定微信，或已取关", ygUser.getId());
        }
        String tempId = this.getWxMsgTempId(WxMessageType.MemberUpgrade);
        String url = promotionLink + link;
        TemplateMessage tplMessage = new TemplateMessage(ygUser.getOpenId(), tempId, title, url);
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", memberLevel);
        tplMessage.pushItem("keyword2", "#323232", checkStatus);
        tplMessage.pushItem("remark", "#323232", remark == null ? "" : remark);
        return this.sendTemplateMessage(tplMessage);
    }

    @Override
    public Message sendTodoTasks(YgUser ygUser, String title, String content, Date dateTime, String remark, String link) {
        if (ygUser == null || StringUtils.isBlank(ygUser.getOpenId())) {
            return Message.error("该用户未绑定微信，或已取关", ygUser.getId());
        }
        String tempId = this.getWxMsgTempId(WxMessageType.TodoTasks);
        String url = promotionLink + link;
        TemplateMessage tplMessage = new TemplateMessage(ygUser.getOpenId(), tempId, title, url);
        tplMessage.pushHead("#323232", title);
        tplMessage.pushItem("keyword1", "#323232", content);
        tplMessage.pushItem("keyword2", "#323232", DateConvertUtils.formatDateTime(dateTime));
        tplMessage.pushItem("remark", "#323232", remark == null ? "" : remark);
        return this.sendTemplateMessage(tplMessage);
    }

}
